package es.ats.codington.spring.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import es.ats.codington.festival.domain.Event;
import es.ats.codington.festival.domain.EventSignUp;
import es.ats.codington.festival.domain.People;
import es.ats.codington.festival.domain.Visitor;
import es.ats.codington.festival.services.EventService;
import es.ats.codington.festival.services.EventSignUpService;
import es.ats.codington.festival.services.VisitorService;


/**
 * @author Codington_RED
 *
 */

@Controller
public class VisitorsController {
	
	/**
	 * Redirects "registervisitor.jsp"
	 * @param request
	 * @param response
	 * @return "registervisitor.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/registervisitor.htm", method=RequestMethod.GET)
	public String registerVisitorGetController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		return "registervisitor";
	}
	
	/**
	 * Register a visitor
	 * @param request
	 * @param response
	 * @return "login.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/registervisitor.htm", method=RequestMethod.POST)
	public String registerVisitorPostController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		try{
			People people = new People();
		
			String n1=request.getParameter("name1");
			String n2=request.getParameter("name2");
			String d=request.getParameter("dni");
		    String u=request.getParameter("username");
		    String p1=request.getParameter("password1");
		    String p2=request.getParameter("password2");
		    String e=request.getParameter("email");
		    String t=request.getParameter("phone");
			String a=request.getParameter("address");
		
			VisitorService service = new VisitorService();
		
			people.setFirstName(n1);
		    people.setLastName(n2);
		    people.setDni(d);
		    people.setEmail(e);
		    people.setPhoneNumber(t);
		    people.setAddress(a);
		    
		    Visitor visitor = new Visitor();
		    visitor.setUserName(u);
		    visitor.setPassword(p1);
	    
	    
	    	/**
	    	 * If the visitor is already registered
	    	 */
			if(service.checkPeople(people)){
				
				request.setAttribute("error", "Known people, please try again");
				
				/**
			     * Redirects "login.jsp"
			     */
				return "login";
			      
			    /**
			     * If the visitor is not registered
			     */
			}  else {  
			  	
				/**
				 * The visitor is recorded
				 */
				service.createVisitor(people);
				
				visitor.setVisitorId(people.getIdPeople());
				service.createVisitorV(visitor);
				
				request.getSession().setAttribute("username", visitor.getUserName());
				request.getSession().setAttribute("password", visitor.getPassword());
				
			
				
				/**
			     * Redirects "login.jsp"
			     */
				return "login";
			}
			
		} catch (Exception e) {
			
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			return "error";
			
		}
		
	}
	
	/**
	 * LogOut
	 * @param request
	 * @param response
	 * @return "login.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/login.htm", method=RequestMethod.GET)
	public String loginVisitorGetController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		request.getSession().invalidate();
		return "login";
	}
	
	/**
	 * LogIn
	 * @param request
	 * @param response
	 * @return "adminvisitor.jsp" or "personal.htm"
	 * @throws IOException
	 */
	@RequestMapping(value="/login.htm", method=RequestMethod.POST)
	public String loginVisitorPostController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		try{
			
			Visitor visitor = new Visitor();
			
			String n=request.getParameter("username");  
			String p=request.getParameter("password");
			
			VisitorService service = new VisitorService();
			
			visitor.setUserName(n);
		    visitor.setPassword(p);
			
		    if(service.checkLogin(visitor)){
				
				/**
				 * If the visitor is admin
				 */
				if(service.checkAdmin(visitor)){
					
					
					request.getSession().setAttribute("visitor", visitor);
					request.getSession().setAttribute("admin", visitor.isAdmin());
					request.setAttribute("admin", visitor.isAdmin());
					request.getSession().setAttribute("username", visitor.getUserName());
					request.getSession().setAttribute("password", visitor.getPassword());
					
					
					/**
					 * Redirects "adminvisitor.jsp"
					 */
					return "adminvisitor";
					
				
				/**
				 * If visitor in not admin
				 */
				} else {
					
					
					request.getSession().setAttribute("username", visitor.getUserName());
					request.getSession().setAttribute("password", visitor.getPassword());
					
					
					
					int id = service.getIdVisitor(visitor);
					People people = new People();
					People people2 = new People();
					people.setIdPeople(id);
					people2 = service.searchPeople(people);
					
					request.getSession().setAttribute("firstNamePeople", people2.getFirstName());
					request.getSession().setAttribute("lastNamePeople", people2.getLastName());
					request.getSession().setAttribute("dniPeople", people2.getDni());
					request.getSession().setAttribute("addressPeople", people2.getAddress());
					request.getSession().setAttribute("numberPeople", people2.getPhoneNumber());
					request.getSession().setAttribute("emailPeople", people2.getEmail());
					
					
					/**
					 * Redirects "personal.htm"
					 */
					
					return "redirect:/personal.htm";
				}
				
		    } else {
		    	/**
				 * Redirects error.jsp
				 */
		    	request.setAttribute("error", "Unknown user, please try again");
		    	return "login";
		    }
		    
		} catch (Exception e) {
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			return "error";
		}
		
			
	}
	
	/**
	 * Redirects "updatevisitor.jsp"
	 * @param request
	 * @param response
	 * @return "updatevisitor.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/updatepeople.htm", method=RequestMethod.GET)
	public String updatePeopleGetController(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		return "updatevisitor";
	}
	
	/**
	 * Update people
	 * @param request
	 * @param response
	 * @return "personal.htm"
	 * @throws IOException
	 */
	@RequestMapping(value="/updatepeople.htm", method=RequestMethod.POST)
	public String updatePeoplePostController(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		try{
			
			int idVisitor = 0;
			
			String n1=request.getParameter("name1");
			String n2=request.getParameter("name2");
			String d=request.getParameter("dni");
			String em=request.getParameter("email");
			String ph=request.getParameter("phone");
			String ad=request.getParameter("address");
			
			String n=(String) request.getSession().getAttribute("username");
			
			VisitorService service = new VisitorService();
			
			Visitor v = new Visitor();
			v.setUserName(n);
			
			idVisitor = service.getIdVisitor(v);
			
			People people = new People();
			
			people.setFirstName(n1);
			people.setLastName(n2);
			people.setDni(d);
			people.setEmail(em);
			people.setPhoneNumber(ph);
			people.setAddress(ad);
			people.setIdPeople(idVisitor);
			
			service.updateVisitor(people);
			
			request.getSession().setAttribute("firstNamePeople", people.getFirstName());
			request.getSession().setAttribute("lastNamePeople", people.getLastName());
			request.getSession().setAttribute("dniPeople", people.getDni());
			request.getSession().setAttribute("addressPeople", people.getAddress());
			request.getSession().setAttribute("numberPeople", people.getPhoneNumber());
			request.getSession().setAttribute("emailPeople", people.getEmail());
			
			/**
			 * Redirects "personal.htm"
			 */
			return "redirect:/personal.htm";
			
		} catch(Exception e) {
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			return "error";
		}
		
	}
	
	/**
	 * Redirects "updatepassword.jsp"
	 * @param request
	 * @param response
	 * @return "updatepassword.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/changepassword.htm", method=RequestMethod.GET)
	public String changePasswordVisitorGetController(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		return "updatepassword";
	}
	
	/**
	 * Change password
	 * @param request
	 * @param response
	 * @return "personal.htm" or "updatepassword.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/changepassword.htm", method=RequestMethod.POST)
	public String changePasswordVisitorPostController(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		try{
			
			String op=request.getParameter("oldpassword");
			String p1=request.getParameter("password1");
			String n=(String) request.getSession().getAttribute("username");
			String p=(String) request.getSession().getAttribute("password");
			
			 VisitorService service = new VisitorService();
			    
			 Visitor visitor = new Visitor();
			 visitor.setUserName(n);
			 visitor.setPassword(p1);
			 
			 if(op.equals(p)){
		    		
		    		/**
		    		 * The password is updated
		    		 */
		    		service.changePassword(visitor);
		    		
		    		 /**
					 * Redirects "personal.htm"
					 */
		    		request.getSession().setAttribute("password", visitor.getPassword());
		    		
		    		return "redirect:/personal.htm";
		    		
		    	/**
		    	 * If not equals newpassword and oldpassword
		    	 */
		    	} else {
		    		
		    		request.setAttribute("error", "Unknown password, please try again");
		    		/**
					 * Redirects "updatepassword.jsp"
					 */
		    		return "updatepassword";
					
		    	}
		    	
			
		} catch(Exception e) {
			
			request.setAttribute("error", e.getMessage());
			return "error";
			
		}    
	 
	}
	
	/**
	 * The visitor to an event is recordered
	 * @param request
	 * @param response
	 * @return "personal.htm" or "AlreadyRegistered.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/registertoevent.htm", method=RequestMethod.POST)
	public String registerVisitorToEventPostController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try{
			
			int idVisitor = 0;
			int idEvent1 = 0;
			
			EventSignUpService service = new EventSignUpService();
			EventSignUp eventsu = new EventSignUp();
			EventService eservice = new EventService();
			Event ev = new Event();
			
			String n=(String) request.getSession().getAttribute("username");
			
	        VisitorService vservice = new VisitorService();
			
			Visitor v = new Visitor();
			v.setUserName(n);
			
			idVisitor = vservice.getIdVisitor(v);
			/**
			 * Get the id of event
			 */
			idEvent1 = Integer.parseInt(request.getParameter("idEventAll"));
		
			
			eventsu.setIdVisitor(idVisitor);
			eventsu.setIdEvent(idEvent1);
			
			/**
			 * If the visitor is not registered at the event
			 */
		    if(!service.checkEventsofVisitor(eventsu)){	
		    	
		    	/**
		    	 * The visitor is recorded in the event
		    	 */
		    	service.registerVisitorToEvent(eventsu);
		    	
		    	ev.setEventID(idEvent1);
		    	/**
		    	 * Available seats decrement event
		    	 */
		    	eservice.updateSeatsEventDec(ev);
		    	
		    	/**
				 * Redirects "personal.htm"
				 */
		    	
		    	return "redirect:/personal.htm";
		    
		    	/**
		    	 * If the visitor is registered in the event
		    	 */
		    } else {
		    	/**
		    	 * Redirects "AlreadyRegistered.jsp"
		    	 */
		    	return "AlreadyRegistered"; 	
		    	
		    }
			
		} catch(Exception e){
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			return "error";
		}
		
	}
	
	/**
	 * To visitor to an event is unregistered
	 * @param request
	 * @param response
	 * @return "personal.htm"
	 * @throws IOException
	 */
	@RequestMapping(value="/unregistertoevent.htm", method=RequestMethod.POST)
	public String unRegisterVisitorToEventPostController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try{
			
			int idVisitor = 0;
			int idEvent1 = 0;
	        
			HttpSession session = request.getSession(true);
			
			EventSignUpService service = new EventSignUpService();
			EventSignUp eventsu = new EventSignUp();
			EventService eservice = new EventService();
			Event ev = new Event();
			
			String n=(String) session.getAttribute("username");
			
	        VisitorService vservice = new VisitorService();
			
			Visitor v = new Visitor();
			v.setUserName(n);
			
			idVisitor = vservice.getIdVisitor(v);
			/**
			 * Get the id of event
			 */
			idEvent1 = Integer.parseInt(request.getParameter("idEventMy"));
			
			eventsu.setIdVisitor(idVisitor);
			eventsu.setIdEvent(idEvent1);
			
			ev.setEventID(idEvent1);
			
			/**
	    	 * The visitor is unregistered in the event
	    	 */
		    service.unregisterVisitorToEvent(eventsu);
		    /**
	    	 * Available seats increment event
	    	 */
		    eservice.updateSeatsEventInc(ev);
		    /**
			 * Redirects "personal.htm"
			 */
		    
		    return "redirect:/personal.htm";
			
		} catch(Exception e){
			
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			return "error";
		}
		
	}
	
	/**
	 * Home of visitor
	 * @param request
	 * @param response
	 * @return "personalvisitor.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/personal.htm")
	public ModelAndView showVisitorPostController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		ModelAndView modelandview = new ModelAndView();
		
		try{
			
		
			int idVisitor = 0;
			VisitorService vservice = new VisitorService();
			EventSignUp esu = new EventSignUp();
			EventService service3 = new EventService();
			EventSignUpService eservice = new EventSignUpService();
			List<Event> events = new ArrayList<Event>();
			List<Event> eventsRegistered = new ArrayList<Event>();
			
			
			events = service3.getAllEvents();
			
			Visitor v = new Visitor();
			
			String n=(String) request.getSession().getAttribute("username");
	
			v.setUserName(n);
			
			idVisitor = vservice.getIdVisitor(v);
			esu.setIdVisitor(idVisitor);
			
			eventsRegistered = eservice.registeredEvents(esu);
			
			List<Integer> listID = new ArrayList<Integer>();
			for(int i = 0; i < eventsRegistered.size(); i++){
				listID.add(i, eventsRegistered.get(i).getEventID());
			}
			
			
			modelandview.addObject("listIdEvents", listID);
			
			modelandview.addObject("eventsRegisteredList", eventsRegistered);
			modelandview.addObject("eventsList", events);
			/**
			 * Redirects "personalvisitor.jsp"
			 */
			modelandview.setViewName("personalvisitor");
			
			return modelandview;
	
			
		} catch(Exception e){
			
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			modelandview.setViewName("error");
			return modelandview;
			
		}
		
		
			
	}
	
}
